package com.cszy.yydqbfq.ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.hbcysd.qybfq.R
import com.hbcysd.qybfq.databinding.FragmentIndexBinding

import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.adapter.indexGridAdapter
import com.cszy.yydqbfq.base.BaseVMFragment
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.AppConstants
import com.cszy.yydqbfq.common.PlaylistRepository

import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.dialog.FcmFirstDialog
import com.cszy.yydqbfq.dialog.FcmShowDialog
import com.cszy.yydqbfq.dialog.FunctionGuideDialog
import com.cszy.yydqbfq.dialog.PermissoTipDialog
import com.cszy.yydqbfq.dialog.UserAgreementDialog
import com.cszy.yydqbfq.dialog.UserRefusedPermissonDialog
import com.cszy.yydqbfq.ext.launch
import com.cszy.yydqbfq.ext.toast

import com.cszy.yydqbfq.ui.activity.MusicListActivity
import com.cszy.yydqbfq.ui.activity.PlayDetailActivity
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.utils.TimeUtils
import com.cszy.yydqbfq.viewmodel.IndexViewModel
import com.cszy.yydqbfq.viewmodel.MainViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils

import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import kotlinx.coroutines.launch
import org.litepal.LitePal


class IndexFragment : BaseVMFragment<IndexViewModel, FragmentIndexBinding>(), IAdViewListener {

    private var adapter: indexGridAdapter? = null
    private var listAdapter: IndexListAdapter? = null
    private var listIndexData: List<MusicListBean>? = null
    private var newGromoreFeedAd : NewGroMoreFeedAdManager? =null

    private var fcmDialog: FcmFirstDialog? = null
    private var fcmshowDialog: FcmShowDialog? = null

    var type_proces: String? = null //功能入口类型
    var app_process: String? = "0" //整个应用流程
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.init(requireActivity())
        mBinding?.apply {
            layoutCommonTitle.tvHomeTitle.text = "首页"
        }
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
    }


    override fun initData() {
        when (app_process) {
            "0" -> showFCM()
            "1" -> app_process_1()
            "2" -> app_process_2()
        }

        newGromoreFeedAd = NewGroMoreFeedAdManager(requireActivity(), BaseAdConstants.FEEDAD_Id, mBinding?.feedContainer,23)
        newGromoreFeedAd?.loadAd()

        //获取音频数据
        mViewModel.queryMusic()
        //设置首页的网格布局
        adapter = indexGridAdapter()
        // 关键代码：创建2行3列的横向GridLayoutManager
        val layoutManager =
            GridLayoutManager(requireContext(), 3, GridLayoutManager.VERTICAL, false)

        mBinding.recyIndexGrid.layoutManager = layoutManager

        mBinding.recyIndexGrid.adapter = adapter

        adapter?.submitList(mViewModel.getIndexGridData())
        //所有列表数据
        listAdapter = IndexListAdapter()
        mBinding.recyIndexList.layoutManager = LinearLayoutManager(requireContext())
        mBinding.recyIndexList.adapter = listAdapter
        initBanner()
    }

    private fun initHorizontalScroll(beans: List<MusicListBean>?) {
        val layoutTodayRecommend = mBinding?.layoutTodayRecommend
        layoutTodayRecommend?.removeAllViews()

        if (beans.isNullOrEmpty()) return

        // 随机选择6个数据
        beans.forEach { bean ->
            val itemView = LayoutInflater.from(requireContext()).inflate(
                R.layout.item_today_recommend,
                layoutTodayRecommend,
                false
            )

            // 设置封面图片
            itemView.findViewById<ImageView>(R.id.iv_recommend_cover)?.let { imageView ->
                Glide.with(this)
                    .load(bean.imageUrl)
                    .placeholder(R.mipmap.ic_default)
                    .error(R.mipmap.ic_default)
                    .apply(RequestOptions.circleCropTransform())
                    .into(imageView)
            }

            // 设置标题和艺术家
            if (app_process == "0") {
                itemView.findViewById<TextView>(R.id.tv_recommend_title)?.text = bean.alias ?: ""
            } else {
                itemView.findViewById<TextView>(R.id.tv_recommend_title)?.text = bean.name ?: ""
            }
            itemView.findViewById<TextView>(R.id.tv_recommend_artist)?.text =
                mViewModel.getRandomTag()

            // 设置点击事件
            itemView.setOnClickListener {
                // 转换为SongInfo并播放
                val songInfo = mViewModel.convertToSongInfoList(listOf(bean))
                val intent = Intent(context, PlayDetailActivity::class.java).apply {
                    putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songInfo))
                    putExtra("CURRENT_POSITION", 0)
                }
                context?.startActivity(intent)
            }

            layoutTodayRecommend?.addView(itemView)
        }
    }

    private fun initBanner() {
        val bannerAdapter = IndexBannerAdapter.getInstance() // 使用你已有的 BannerAdapter
        mBinding.apply {
            viewPagerBanner.adapter = bannerAdapter
            // 修复指示器类型问题，使用 arrayOf 而不是 listOf
            val indicators = arrayOf(indicator1, indicator2, indicator3)

            bannerAdapter.setOnItemClickListener { adapter, view, position ->
                val bundle = Bundle()
                // 确保 getBannerCategory() 方法在 ViewModel 中存在
                bundle.putString("category", adapter.items?.get(position)?.title ?: "")
                launch(bundle, MusicListActivity::class.java)
            }

            // 设置页面切换监听器，同步更新指示器
            viewPagerBanner.registerOnPageChangeCallback(object :
                androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    // 更新指示器状态
                    mViewModel.updateIndicators(indicators, position)
                }
            })

            // 传入数组类型的指示器
            mViewModel.startBannerAutoScroll(viewPagerBanner, indicators)
            // 设置 Banner 大小
            mViewModel.setBannerSize(bannerAdapter.itemCount)
        }
    }


    override fun initObserve() {
        //获取音频数据
        mViewModel.queryMusicResult.observe(this) { musiclist ->
            Log.e("IndexFragment", "musiclist:" + musiclist.toString())
            listIndexData = musiclist as List<MusicListBean>?
            listAdapter?.submitList(musiclist as List<MusicListBean>?)
            initHorizontalScroll(musiclist as List<MusicListBean>?)
        }
    }

    override fun initListener() {
        //每次间隔30秒弹插屏
        var lastScrollTime = 0L // 记录上次触发时间
        mBinding.nestScrll.setOnScrollChangeListener { _, _, scrollY, _, oldScrollY ->
            val dy = scrollY - oldScrollY // 计算滚动距离差（dy > 0 表示上滑）
            if (dy > 0) { // 仅在上滑时触发
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastScrollTime > 30_000) { // 30秒 = 30,000毫秒
                    AdManager.loadChapin_nocache(
                        requireActivity(),
                        2,
                        this,
                        object : AdLoadListener {
                            override fun onAdLoadFailed(ad: IAdView?) {

                            }
                        })
                    lastScrollTime = currentTime // 更新最后一次触发时间
                }
            }
        }


        listAdapter?.setOnItemClickListener { adapter, view, position ->
            // 传递整个列表和当前点击位置
            var songList = mViewModel.convertToSongInfoList(adapter.items)
            val intent = Intent(context, PlayDetailActivity::class.java).apply {
                putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songList))
                putExtra("CURRENT_POSITION", position)
            }
            context?.startActivity(intent)

        }
        // 需要传递控件 id加入歌单点击事件
        listAdapter?.addOnItemChildClickListener(R.id.tv_add_gedanlist) { adapter, view, position ->
            // toast("点了添加歌单")
            var song_item = adapter.items.get(position)
            // 将 MusicListBean 转换为 Song
            val song = Song().apply {
                title = song_item.name ?: ""
                artist = song_item.author ?: ""
                cover = song_item.imageUrl ?: ""
                uri = song_item.songUrl
                duration = 0
                songlistbean_id = 0
            }
            val repository = PlaylistRepository()
            var geDanList = repository.getAllPlaylists()
                .filter { it.name != "本地音乐" }  // 过滤条件
            BottomPopupWithGeDanRecycler(requireActivity(), geDanList, song).show(requireView())
        }

        //grid音乐列表
        adapter?.setOnItemClickListener { adapter, view, position ->
            var bundle = Bundle()
            bundle.putString("category", adapter.getItem(position)?.title.toString())
            launch(bundle, MusicListActivity::class.java)
        }
        //本地音乐获取
        mBinding.rvImportLocal.setOnClickListener {
            showMediaPermissionDialog()
        }
        //进入本地音乐播放列表
        mBinding.rvGoLocal.setOnClickListener {
            if (app_process == "0") {
                var bundle = Bundle()
                bundle.putString("category", "本地音乐")
                launch(bundle, MusicListActivity::class.java)
            } else {
                type_proces = "点击本地音乐"
                AdManager.loadVideo_nocache(
                    requireActivity(),
                    19,
                    this@IndexFragment,
                    object : AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
                            var bundle = Bundle()
                            bundle.putString("category", "本地音乐")
                            launch(bundle, MusicListActivity::class.java)
                        }
                    })
            }


        }
    }

    override fun onResume() {
        super.onResume()
        if (app_process == "0") {
            //第一次显示防沉迷diaolog
            if (!SpUtils.getInstance().getBoolean(AppConstants.IS_SHOW_FCM_DIALOG)) {
                showDialog_fcmDialog()
            } else {
                if (fcmDialog != null) {
                    fcmDialog?.dismiss()
                }
                if (fcmshowDialog != null) {
                    fcmshowDialog?.dismiss()
                }
            }

        }


        val localList = LitePal.findAll(AudioItemBean::class.java)
        if (localList.isNotEmpty()) {
            // 更新 UI（）
            mBinding.rvImportLocal.visibility = View.GONE
            mBinding.rvGoLocal.visibility = View.VISIBLE
            mBinding.tvLocalAudioNum.text = localList.size.toString() + "首"
        }
    }

    fun app_process_1() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin_nocache(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.e("qin", "首页流程1插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        if (!isAdded) return
                        showFunctionGuideDialog(requireActivity())
                    }
                }
            })
    }

    fun app_process_2() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin_nocache(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.i("qin", "首页流程2插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        showFunctionGuideDialog(requireActivity())
                    }

                }
            })
    }

    /**
     * 显示功能引导弹窗
     */
    private fun showFunctionGuideDialog(context: Context) {
        // 创建对话框实例
        val dialog = FunctionGuideDialog(context)
        dialog.setCancelable(false) // 设置对话框不可取消
        dialog.setOnGuideDialogListener(object : FunctionGuideDialog.onGuideDialogListener {
            override fun btnOnclick() {
               closeGuide()
            }

            private fun closeGuide() {
                dialog.dismiss() // 关闭对话框
                // 处理点击引导内容的回调
                type_proces = "功能弹窗"
                AdManager.loadVideo_nocache(
                    requireActivity(),
                    4,
                    this@IndexFragment,
                    object : AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
                            if (app_process == "0"){
                                showAgreementtDialog()
                            }
                        }
                    })
            }

            override fun btnOnclose() {
                closeGuide()
            }
        })

// 显示对话框
        dialog.show()
    }



    private fun showInterstitialWithAgree() {
        AdManager.loadChapin_nocache(requireActivity(), 9, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                showAgreementtDialog()
            }
        })
    }

    override fun loadAudioList() {
        showLoading("正在获取本地音乐")
        lifecycleScope.launch { // 使用 lifecycleScope 确保协程与 Activity 生命周期绑定
            try {
                // 调用 suspend 函数获取数据
                val audioList = mViewModel.getAudioInfoListSync()
                dismissLoading()
                // 更新 UI（）
                mBinding.rvImportLocal.visibility = View.GONE
                mBinding.rvGoLocal.visibility = View.VISIBLE
                mBinding.tvLocalAudioNum.text = audioList.size.toString() + "首"

            } catch (e: Exception) {
                // 处理错误（例如 Toast 提示）
                dismissLoading()
                toast("加载音频列表失败: ${e.message}")
            }
        }
    }


    fun showDialog_fcmDialog() {
        SpUtils.getInstance().putBoolean(AppConstants.IS_SHOW_FCM_DIALOG, true)
        fcmDialog = FcmFirstDialog(requireActivity())
        fcmDialog?.setCancelable(false)
        fcmDialog?.show()


    }

    fun showDialog_fcmDialog_open() {
        fcmshowDialog = FcmShowDialog(requireActivity())
        fcmshowDialog?.setCancelable(false)
        fcmshowDialog?.show()
    }

    private fun showFCM() {
        //是否开启显示防沉迷dialog
        if (SpUtils.getInstance().getBoolean(AppConstants.ISOPEN_FCM)) {
            if (TimeUtils.isNightTime()) {
                showDialog_fcmDialog_open()
            }
        }
    }

    /**
     * 显示隐私协议弹窗
     */
    private fun showAgreementtDialog() {
        if (SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {

            return
        }
        var dialog = UserAgreementDialog(requireActivity())
        dialog!!.show()
        dialog!!.setPrivateId(
            "您好" + "(" + BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID) + ")"
        )
        dialog!!.setCancelable(false)
        dialog!!.setOnAgreementListener(object : UserAgreementDialog.AgreementDialogListner {
            override fun onDialogListener(clickType: Boolean) {
                if (clickType) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.isAgreeMent, true)
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN)) {
                        type_proces = "特殊情况点击同意隐私的插屏"
                        AdManager.loadChapin_nocache(
                            requireActivity(),
                            10,
                            this@IndexFragment,
                            object : AdLoadListener {
                                override fun onAdLoadFailed(ad: IAdView?) {


                                }
                            })
                    }

                } else { //拒绝隐私协议
                    activity?.finish()

                }
            }
        })
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {
        when (type_proces) {
            "功能返回插屏" -> {
                SpUtils.getInstance()
                    .putBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN, true)//已经弹过了功能返回的插屏
            }

            "功能弹窗" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG, true)
            }
        }
    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        // 检查 Fragment 是否仍然有效
        if (!isAdded || isDetached || activity == null) {
            return // 如果 Fragment 无效，直接返回
        }
        when (type_proces) {
            "第一次进首页插屏" -> {
                if (!SpUtils.getInstance()
                        .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                ) {
                    showFunctionGuideDialog(requireActivity())
                } else {
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {
                        showAgreementtDialog()
                    }
                }
            }


            "功能弹窗关闭广告" -> {
                if (app_process == "1") {
                    showAgreementtDialog()
                }

            }

            "功能弹窗" -> {
                if (app_process == "1") {
                    type_proces = "功能弹窗关闭广告"
                    showInterstitialWithAgree()
                }
            }

            "点击本地音乐" -> {
                var bundle = Bundle()
                bundle.putString("category", "本地音乐")
                launch(bundle, MusicListActivity::class.java)
            }


        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        mViewModel.stopBannerAutoScroll()
    }
}